import { defineStore } from 'pinia'
import { api, API_PREFIX, API_TSL_FRONTEND } from 'boot/axios'
import { Loading, Notify } from 'quasar'


// For QC WO Review Page
export const useUploadWoStore = defineStore('uploadWo', {
  state: () => ({
    // fgArticles: [],
    updateData: [],
    createData: [],
    errorItems: [],
    fileInfo:[],
    outstandingNum: 0,
    export_os_url: null,
    flow_list: [],
    stone_mount_list: [],
    difficulty_list: [],

    pagination: {
        currentPage: 1,
        rowsPerPage : 10,
        sortCol : null,
        sortDirection : 'desc',
        total : 0,
        max : 1,
    }
  }),

  getters: {
    
  },
    actions: {
        init(){
            // this.fgArticles = []
            this.createData = []
            this.updateData = []
            this.fileInfo = []
            this.outstandingNum = 0
            this.export_os_url = null
        },

        async loadUploadWOPage(){
            Loading.show()
            try{
                const res = await api.get(API_TSL_FRONTEND + '/OutstandingMaster/')
                console.log('loadUploadWOPage result: ', res)
                this.outstandingNum = res.data.data.total_count
                Loading.hide()
                return true
            }catch (error){
                console.log(error.response)
                Loading.hide()
                return false
            }
        },

        async uploadFile(formData) {
            Loading.show()
            try{
                const res = await api.post(API_TSL_FRONTEND + '/uploadRoutingTable'+ '/importExcel/', formData)
                // console.log('upload FG article File result: ', res)
                this.fileInfo = res.data.info
                // console.log('fileInfo: ', this.fileInfo)
                console.log(res.data);
                this.updateData = res.data.update_data
                this.createData = res.data.create_data
                // console.log('fgArticles: ', this.fgArticles)
                this.errorItems = res.data.errorList
                // console.log('errorItems: ', this.errorItems)
                this.outstandingNum = res.data.outstanding_count
                // console.log('outstandingNum: ', this.outstandingNum)
                Loading.hide()
                return true
            }catch (error){
                console.log(error)
                Loading.hide()
                Notify.create({
                    message: error.response?.data.message??'Upload Failed',
                    color: 'negative',
                    timeout: 2000,
                    position: "center",
                })
                return false
            }
        },

        async searchFGarticle(params){
            Loading.show()
            try{
                console.log(params)
                this.pagination.rowsPerPage = params.rows_per_page
                const res = await api.post(API_TSL_FRONTEND + '/uploadRoutingTable'+'/searchFGArticle/', params)
                const data = res.data.result // array
                const flow_list = res.data.flows
                const stone_mount_list = res.data.stone_mount_data
                const difficulty_list = res.data.difficulty_data
                console.log('search FG article result data: ', data)
                this.createData = data.results // 这里由于公用了原为fgArticles
                this.flow_list = flow_list
                this.stone_mount_list = stone_mount_list
                this.difficulty_list = difficulty_list

                this.pagination.total = data.count
                this.pagination.max = Math.ceil(data.count / this.pagination.rowsPerPage)

                console.log('pagination: ', this.pagination);
                console.log('search FG article flow_list: ', flow_list)
                console.log('search FG article difficulty_list: ', difficulty_list)
                console.log('search FG article stone_mount_list: ', stone_mount_list)
                Loading.hide()
                return true
            }catch(error){
                console.log(error)
                Loading.hide()
                return false
            }
        },

        getFGArticle(fgArticle_id){
            const created = this.createData.find(fg => fg.master_id === fgArticle_id)
            if (created){
                return created
            }else{
                return this.updateData.find(fg => fg.master_id === fgArticle_id)
            }
        },

        updateFGArticle(updatedFGArticles){
            this.createData = updatedFGArticles
        },
        updateFGArticle2(updatedFGArticles){
            this.updateData = updatedFGArticles
        },

        async saveFGArticle(master_id , is_one_inlay, flows) {
            Loading.show()
            const rf = []
            let seq = 0
            flows.forEach(e => {
                seq += 1
                const temp = {
                    "seq": seq,
                    "routeName": e.routeName,
                    "qty": e.qty,
                    "difficulty": e.difficulty,
                    "psName": e.psName,
                    "ssName": e.ssName,
                    "consumePercent": e.consumePercent,
                    "workfee": e.workfee
                }
                rf.push(temp)
            });
            // call api
            const params = {
                master_id: master_id,
                single_job: (is_one_inlay === '是') ? true : false,
                route_flows: rf
            }
            console.log('params: ', params)
            try {
                const res = await api.post(API_TSL_FRONTEND + '/uploadRoutingTable' + '/saveChanges/', params)
                console.log('saveFGArticle result: ', res)
                let edit_fg = this.createData.findIndex(fg => fg.master_id === master_id)
                if(edit_fg !== -1){
                    console.log('edit_fg: ', edit_fg)
                    this.createData[edit_fg].is_one_inlay = is_one_inlay
                    this.createData[edit_fg].item = rf

                }
                let edit_fg2 = this.updateData.findIndex(fg => fg.master_id === master_id)
                if(edit_fg2 !== -1){
                    console.log('edit_fg2: ', edit_fg2)
                    this.updateData[edit_fg].is_one_inlay = is_one_inlay
                    this.updateData[edit_fg].item = rf
                }
                Loading.hide()
                return true
            } catch (error) {
                console.log('error?? ', error)
                Loading.hide()
                return false
            }
        },

        async exportOustandingMaster(){
            Loading.show()
            try{
                const res = await api.get(API_TSL_FRONTEND + '/OutstandingMaster/' + 'export_csv/')
                console.log('exportOustandingMaster result: ', res)
                
                const export_url = window.URL.createObjectURL(new Blob([res.data], { type: 'text/csv' }))
                console.log('export_url: ', export_url)
                this.export_os_url = export_url
                
                Loading.hide()
                return true
            }catch (error){
                console.log(error.response)
                Loading.hide()
                return false
            }
        }
    }
})
